import os
import argparse
from difflib import Differ

def count_line_diffs(file1_path, file2_path):
    """比较两个文件的内容，返回不同的行数"""
    try:
        with open(file1_path, 'r', encoding='utf-8', errors='ignore') as f1, \
             open(file2_path, 'r', encoding='utf-8', errors='ignore') as f2:
            
            lines1 = f1.readlines()
            lines2 = f2.readlines()
            
            differ = Differ()
            diffs = list(differ.compare(lines1, lines2))
            
            # 统计不同的行数（以'+'、'-'或'?'开头的行）
            diff_line_count = sum(1 for line in diffs if line.startswith(('+', '-', '?')))
            return diff_line_count
            
    except Exception as e:
        print(f"比较文件时出错 {file1_path} 和 {file2_path}: {str(e)}")
        return -1

def compare_folders(folder1, folder2, output_results=True):
    """递归比较两个文件夹，返回差异结果"""
    results = []
    
    # 获取两个文件夹中的所有条目
    items1 = set(os.listdir(folder1)) if os.path.exists(folder1) else set()
    items2 = set(os.listdir(folder2)) if os.path.exists(folder2) else set()
    
    # 处理两个文件夹共有的条目
    common_items = items1 & items2
    for item in sorted(common_items):
        path1 = os.path.join(folder1, item)
        path2 = os.path.join(folder2, item)
        
        if os.path.isdir(path1) and os.path.isdir(path2):
            # 递归比较子文件夹
            sub_results = compare_folders(path1, path2, output_results=False)
            results.extend(sub_results)
            
        elif os.path.isfile(path1) and os.path.isfile(path2):
            # 比较文件内容
            diff_count = count_line_diffs(path1, path2)
            if diff_count > 0:
                relative_path = os.path.relpath(path1, folder1)
                results.append((relative_path, diff_count))
                if output_results:
                    print(f"文件 {relative_path} 有 {diff_count} 行不同")
    
    # 处理仅在第一个文件夹中存在的条目
    for item in sorted(items1 - items2):
        path = os.path.join(folder1, item)
        relative_path = os.path.relpath(path, folder1)
        results.append((relative_path, f"仅在 {folder1} 中存在"))
        if output_results:
            print(f"文件 {relative_path} 仅在 {folder1} 中存在")
    
    # 处理仅在第二个文件夹中存在的条目
    for item in sorted(items2 - items1):
        path = os.path.join(folder2, item)
        relative_path = os.path.relpath(path, folder2)
        results.append((relative_path, f"仅在 {folder2} 中存在"))
        if output_results:
            print(f"文件 {relative_path} 仅在 {folder2} 中存在")
    
    return results

def main():
    parser = argparse.ArgumentParser(description='递归比较两个文件夹中的文件差异')
    parser.add_argument('folder1', help='第一个文件夹路径')
    parser.add_argument('folder2', help='第二个文件夹路径')
    
    args = parser.parse_args()
    
    # 验证文件夹路径
    if not os.path.isdir(args.folder1):
        print(f"错误: {args.folder1} 不是有效的文件夹路径")
        return
    
    if not os.path.isdir(args.folder2):
        print(f"错误: {args.folder2} 不是有效的文件夹路径")
        return
    
    print(f"正在比较 {args.folder1} 和 {args.folder2} ...\n")
    compare_folders(args.folder1, args.folder2)

if __name__ == "__main__":
    main()
    